import React, { useState, useEffect } from "react";
import styles from "./index.less";
import {
  Card,
  Table,
  Button,
  Input,
  Space,
  Form,
  Modal,
  message,
  Popconfirm,
} from "antd";
import {
  PlusOutlined,
  SearchOutlined,
  DeleteOutlined,
  EditOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import { auth } from "@/utils/auth";
import moment from "moment";
import { useNavigate } from 'umi';

interface DeviceData {
  // key: string;           // 设备唯一标识
  deviceName: string;    // 设备名称
  device_imei1: string;         // IMEI1号码
  device_imei2: string;         // IMEI2号码
  mem: string;        // 内存
  sdcard: string;       // 存储
  useman: string;          // 使用人
  price: string;         // 价格
  createdAt: string;     // 创建时间
  // deviceId: string;      // 设备ID
  id:string;
}

const DevicePage: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [isEditModalVisible, setIsEditModalVisible] = useState(false);
  const [editForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [currentEditDevice, setCurrentEditDevice] = useState<DeviceData | null>(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [data, setData] = useState<DeviceData[]>([]);
  const [searchParams, setSearchParams] = useState({
    deviceName: "",
    imei: "",
  });

  const navigate = useNavigate();

  // 获取设备列表数据
  const fetchDeviceList = async (page: number = pagination.current) => {
    try {
      setLoading(true);
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      // 构建查询参数
      const queryParams = new URLSearchParams({
        page: page.toString(),
        limit: pagination.pageSize.toString(),
        search: searchParams.deviceName,
        imei: searchParams.imei,
      });

      const response = await fetch(
        // `/agentapi/devices?${queryParams.toString()}`,
        `/agentapi/api/t-device?${queryParams.toString()}`,
        {
          method: "GET",
          headers: {
            Authorization: `Bearer ${await auth.getValidAccessToken()}`,
          },
        }
      );

      if (response.status === 200) {
        const result = await response.json();
        if (Array.isArray(result.data)) {
          const formattedData = result.data.map((item: any) => ({
            // key: item.id,
            deviceName: item.name || item.deviceName,
            device_imei1: item.device_imei1 || '',
            device_imei2: item.device_imei2 || '',
            mem: item.mem || '',
            sdcard: item.sdcard || '',
            useman: item.useman || '',
            price: item.price || '',
            createdAt: item.createdAt,
            // deviceId: item.id,
            id:item.id
          }));
          setData(formattedData);
          setPagination({
            current: page,
            pageSize: pagination.pageSize,
            total: result.pagination?.total || 0,
          });
        } else {
          message.error(result.message || "获取设备列表失败");
        }
      } else {
        message.error("获取设备列表失败");
      }
    } catch (error) {
      message.error("获取设备列表失败，请检查网络连接");
    } finally {
      setLoading(false);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    // fetchDeviceList(1);
  }, []); // 只在组件挂载时执行一次

  // 当搜索参数变化时，重新获取数据
  useEffect(() => {
    fetchDeviceList(1);
  }, [searchParams]);

  console.log('t_device：auth.getValidAccessToken()=======',auth.getValidAccessToken());


  const handleDelete = async (record: DeviceData) => {
    try {
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch(`/agentapi/api/t-device/${record.id}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
      });

      if (response.status === 200) {
        message.success("删除成功");
        fetchDeviceList(); // 重新获取列表
      } else {
        message.error("删除失败");
      }
    } catch (error) {
      message.error("删除失败，请检查网络连接");
    }
  };

  const handleSearch = (values: any) => {
    setSearchParams({
      deviceName: values.search || "",
      imei: values.imei || "",
    });
  };

  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({
      deviceName: "",
      imei: "",
    });
  };

  const handleEdit = (record: DeviceData) => {
    setCurrentEditDevice(record);
    editForm.setFieldsValue({
      // name: record.deviceName,
      device_imei1: record.device_imei1 || '',
      device_imei2: record.device_imei2 || '',
      // mem: record.mem || '',
      // sdcard: record.sdcard || '',
      // useman: record.useman || '',
      // price: record.price || '',
      id:record.id
    });
    setIsEditModalVisible(true);
  };

  const handleEditCancel = () => {
    setIsEditModalVisible(false);
    setCurrentEditDevice(null);
    editForm.resetFields();
  };

  const handleEditSubmit = async () => {
    try {
      const values = await editForm.validateFields();
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch(`/agentapi/api/t-device/${currentEditDevice?.id}`, {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
        body: JSON.stringify(values),
      });

      if (response.status === 200) {
        message.success("编辑成功");
        setIsEditModalVisible(false);
        setCurrentEditDevice(null);
        editForm.resetFields();
        fetchDeviceList(); // 重新获取列表
      } else {
        message.error("编辑失败");
      }
    } catch (error) {
      message.error("编辑失败，请检查网络连接");
    }
  };

  const columns: ColumnsType<DeviceData> = [
    // {
    //   title: "设备名",
    //   dataIndex: "deviceName",
    //   key: "deviceName",
    // },
    {
      title: "IMEI1",
      dataIndex: "device_imei1",
      key: "device_imei1",
    },
    {
      title: "IMEI2",
      dataIndex: "device_imei2",
      key: "device_imei2",
    },
    {
      title: "存储",
      dataIndex: "sdcard",
      key: "sdcard",
    },
    {
      title: "内存",
      dataIndex: "mem",
      key: "mem",
    },
    {
      title: "创建时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (createdAt) => {
        return moment.utc(createdAt).format("YYYY-MM-DD HH:mm:ss");
      },
    },
    {
      title: "使用人",
      dataIndex: "useman",
      key: "useman",
    },
    {
      title: "价格",
      dataIndex: "price",
      key: "price",
    },
    {
      title: "操作",
      key: "operation",
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="删除设备"
            description="确定要删除这个设备吗？此操作不可恢复。"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div className={styles.container}>
      <Card>
        <div style={{ display: "flex", justifyContent: "space-between" }}>
          <Form
            form={searchForm}
            layout="inline"
            onFinish={handleSearch}
            className={styles.searchForm}
          >
            <Form.Item name="search">
              <Input
                placeholder="请输入设备名称"
                prefix={<SearchOutlined />}
                allowClear
              />
            </Form.Item>

            <Form.Item name="imei">
              <Input
                placeholder="请输入IMEI"
                prefix={<SearchOutlined />}
                allowClear
              />
            </Form.Item>
            

            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
              </Space>

            </Form.Item>
          </Form>
          <div className={styles.tableHeader}>
            <Button type="primary" icon={<PlusOutlined />} onClick={() => navigate('/addDevice')}>
              添加设备
            </Button>
          </div>
        </div>

        <Table<DeviceData>
          columns={columns}
          dataSource={data}
          rowKey="key"
          loading={loading}
          style={{
            height: `calc(100vh - 260px)`,
            overflow: "auto",
            scrollbarWidth: "none",
          }}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page) => fetchDeviceList(page),
          }}
        />

        <Modal
          title="编辑设备"
          open={isEditModalVisible}
          onOk={handleEditSubmit}
          onCancel={handleEditCancel}
          confirmLoading={loading}
          okText="确定"
          cancelText="取消"
        >
          <Form
            form={editForm}
            layout="horizontal"
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 17 }}
          >
            {/* <Form.Item
              name="name"
              label="设备名称"
              rules={[{ required: true, message: "请输入设备名称" }]}
            >
              <Input placeholder="请输入设备名称" />
            </Form.Item> */}
            <Form.Item
              name="device_imei1"
              label="IMEI1"
              rules={[{ required: true, message: "请输入IMEI1" }]}
            >
              <Input placeholder="请输入IMEI1" />
            </Form.Item>
            <Form.Item
              name="device_imei2"
              label="IMEI2"
            >
              <Input placeholder="请输入IMEI2" />
            </Form.Item>
            <Form.Item
              name="mem"
              label="内存"
            >
              <Input placeholder="请输入内存" />
            </Form.Item>
            <Form.Item
              name="sdcard"
              label="存储"
            >
              <Input placeholder="请输入存储" />
            </Form.Item>
            <Form.Item
              name="useman"
              label="使用人"
            >
              <Input placeholder="请输入使用人" />
            </Form.Item>
            <Form.Item
              name="price"
              label="价格"
            >
              <Input placeholder="请输入价格" />
            </Form.Item>
          </Form>
        </Modal>
      </Card>
    </div>
  );
};

export default DevicePage;
